package com.css.chat.ui.controller;

import com.css.chat.base.SessionManager;
import com.css.chat.base.UiBaseService;
import com.css.chat.logic.login.LoginManager;
import com.css.chat.ui.ControlledStage;
import com.css.chat.ui.R;
import com.css.chat.ui.StageController;
import com.css.chat.util.CommonUtil;
import com.css.chat.util.I18n;
import javafx.beans.binding.Bindings;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;

/**
 * @author zyj
 * @description
 * @date 2019/7/19 16:19
 **/
public class LoginViewController implements ControlledStage, Initializable {
    @FXML
    private Button login;
    @FXML
    private TextField userId;
    @FXML
    private PasswordField password;
    @FXML
    private Pane errorPane;
    @FXML
    private Label errorTips;
    @FXML
    private ProgressBar loginProgress;


    @FXML
    private void logins() {
        final long useId = Long.parseLong(userId.getText());
        final String psw = password.getText();
        if (!SessionManager.INSTANCE.isConnectedSever()) {
            errorPane.setVisible(true);
            errorTips.setText(I18n.get("login.failToConnect"));
            return;
        }

        loginProgress.setVisible(true);
        login.setVisible(false);

        LoginManager.getInstance().beginToLogin(useId, psw);
    }

    @FXML
    private void login_en() {
        login.setStyle("-fx-background-radius:4;-fx-background-color: #097299");
    }

    @FXML
    private void login_ex() {
        login.setStyle("-fx-background-radius:4;-fx-background-color: #09A3DC");
    }

    @FXML
    private void close() {
        System.exit(1);
    }

    @FXML
    private void min() {
        Stage stage = getMyStage();
        if (stage != null) {
            stage.setIconified(true);
        }
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        /**
         * 验证规则：　userId非空且为数字　password非空
         自定义绑定Bindings.createBooleanBinding(...)*/
        login.disableProperty().bind(Bindings.createBooleanBinding(
                ()->userId.getText().length() == 0 ||
                        !CommonUtil.isInteger(userId.getText()) ||
                        password.getText().length() == 0,
                userId.textProperty(),
                password.textProperty()));

    }



    @Override
    public Stage getMyStage() {
        StageController stageController = UiBaseService.INSTANCE.getStageController();
        return stageController.getStageBy(R.id.LoginView);
    }
}
